<!--
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-02 18:39:40
 * @LastEditTime: 2023-10-12 17:16:12
-->
<script lang="ts" setup name="UserEditModal">
import { _, ikStore } from 'iking-utils'
import type { Ref } from 'vue'
import { userApi } from '@/MainApp/apis/user'
import { systemConfig } from '@/system.config'

interface ISex {
  id: string
  label: string
  value: string
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => null
  }
})
const emits = defineEmits<{
  (event: 'cancel'): void
  (event: 'update:visible', value: boolean): void
  (event: 'confirm'): void
}>()
const { user } = systemConfig
const loading = ref(false)
const { dialog, t } = useConfig()
const formKey = {
  name: '',
  nickname: '',
  username: '',
  sex: '',
  phone: '',
  email: '',
  adminUser: false,
  avatar: '',
  birthday: '',
  locked: false,

  deptIds: [] as Array<string>,
  postIds: [] as Array<string>,
  roleIds: [] as Array<string>
}
const { lenPhone, lenName } = useLength()
const userFormRef = ref()
const userForm = ref(formKey)
const { msgSuccess, msgError } = useMessage()
const userRules = useFormRules([
  {
    key: 'name',
    required: user?.name || false,
    trigger: 'blur',
    msg: '请输入姓名'
  },
  {
    key: 'username',
    required: user?.username || false,
    trigger: 'blur',
    msg: '请输入用户名'
  },
  {
    key: 'nickname',
    required: user?.nickname || false,
    trigger: 'blur',
    msg: '请输入昵称'
  },
  {
    key: 'phone',
    required: user?.phone || false,
    trigger: 'blur',
    type: 'phone',
    msg: '请输入手机号',
    typeMsg: '手机号码格式不正确'
  },
  {
    key: 'email',
    type: 'email',
    required: user?.email || false,
    trigger: 'blur',
    msg: '',
    typeMsg: '邮箱格式不正确'
  }
])
const sexList: Ref<ISex[]> = ref([])
const dVisible = ref(props.visible)
watch(
  () => props.visible,
  bool => {
    dVisible.value = bool
  }
)

const handOpen = () => {
  if (props.editData) {
    userForm.value = _.cloneDeep(props.editData as typeof formKey)
    userForm.value.deptIds = props.editData.departments?.map((v: { deptId: any; }) => v.deptId)
    userForm.value.postIds = props.editData.posts?.map((v: { postId: any; }) => v.postId)
    userForm.value.roleIds = props.editData.roles?.map((v: { roleId: any; }) => v.roleId)
  }
  else {
    userForm.value = _.cloneDeep(formKey)
  }
  const dict: { SEX: Array<ISex & { sortOrder: number; }>; } = ikStore.local.getItem(ELocal.DICTIONARY)
  try {
    sexList.value = dict.SEX?.sort((a, b) => a.sortOrder - b.sortOrder)
    // 性别默认第一项
    !userForm.value.sex && (userForm.value.sex = sexList.value[0].value)
  }
  catch (error) {
  }
}
const handCancel = () => {
  emits('update:visible', false)
  emits('cancel')
  userFormRef.value?.resetFields()
}
const handClosed = () => {
  emits('cancel')
  handCancel()
}

const formatStringToArray = (str: Array<string> | string) => {
  return typeof str === 'string' ? [str] : str
}
const handConfirm = async () => {
  userFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      const params = {
        ...userForm.value,
        departments: (userForm.value as any)?.departments?.filter((v: { deptId: string; }) => userForm.value.deptIds.includes(v.deptId)) ?? [],
        deptIds: formatStringToArray(userForm.value.deptIds),
        postIds: formatStringToArray(userForm.value.postIds),
        roleIds: formatStringToArray(userForm.value.roleIds),
        lockType: userForm.value.locked ? 'PERMANENTLY_LOCK' : 'NO_LOCK'
      }
      const { success, msg } = props.editData
        ? await userApi.updateUser(params)
        : await userApi.addUser(params)
      if (success) {
        emits('confirm')
        handCancel()
        msgSuccess(msg)
      }
      else {
        msgError(msg)
      }
      loading.value = false
    }
  })
}
</script>

<template>
  <el-dialog
    v-model="dVisible"
    v-loading="loading"
    :rules="userRules"
    :title="editData ? '修改用户' : '新增用户'"
    :width="dialog.l"
    draggable
    align-center
    :close-on-click-modal="false"
    @closed="handClosed"
    @open="handOpen"
  >
    <el-form
      ref="userFormRef"
      label-position="top"
      :model="userForm"
      :rules="userRules"
      label-width="80px"
    >
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model.trim="userForm.name"
              clearable
              placeholder="请输入姓名"
              :maxlength="lenName"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="userForm.sex">
              <el-radio v-for="item in sexList" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="头像" prop="avatar">
            <IkImageUpload
              v-model:url="userForm.avatar"
              :width="130"
              :height="130"
              notip
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model.trim="userForm.username"
              clearable
              :maxlength="lenName"
              show-word-limit
              placeholder="请输入用户名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickname">
            <el-input
              v-model.trim="userForm.nickname"
              clearable
              :maxlength="lenName"
              show-word-limit
              placeholder="请输入昵称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model.trim="userForm.phone"
              v-number="{ form: userForm, key: 'phone' }"
              :maxlength="lenPhone"
              show-word-limit
              clearable
              placeholder="请输入手机号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model.trim="userForm.email"
              clearable
              :maxlength="lenName"
              placeholder="请输入邮箱"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门" prop="deptIds">
            <IkSelectDep
              v-model="userForm.deptIds"
              placeholder="请选择部门"
              multiple
              check-strictly
              show-checkbox
              collapse-tags
              :max-collapse-tags="2"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位" prop="postIds">
            <IkSelectPost
              v-model="userForm.postIds"
              placeholder="请选择岗位"
              multiple
              check-strictly
              show-checkbox
              collapse-tags
              :max-collapse-tags="2"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="roleIds">
            <IkSelectRole
              v-model="userForm.roleIds"
              placeholder="请选择角色"
              multiple
              check-strictly
              show-checkbox
              collapse-tags
              :max-collapse-tags="2"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="锁定" prop="locked">
            <el-switch
              v-model="userForm.locked"
              inline-prompt
              active-text="锁定"
              inactive-text="不锁定"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button
          bg
          text
          @click="handCancel"
        >{{ t('action.cancel') }}</el-button>
        <el-button
          :loading="loading"
          bg
          type="primary"
          @click="handConfirm"
        >
          {{ t('action.sure') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
